# my_server.py
import json
import ast
import docker
from docker.errors import DockerException
from llm_sandbox import SandboxSession, SandboxBackend
from app.core.repl.security_configuration import PYTHON_POLICY
from fastmcp import FastMCP

mcp = FastMCP(name="MyServer")


@mcp.tool()
def greet(name: str) -> str:
    """Greet a user by name."""
    return f"Hello, {name}!"
@mcp.tool()
def getweather(city: str) -> str:
    """Greet a user by name."""
    return f"{city}天气不错哦!"


@mcp.tool()
def execute_code(lang: str, code: str) -> str:
    """在沙箱环境中执行代码

    Args:
        lang: 编程语言，必须是['python', 'java', 'javascript', 'cpp', 'go', 'ruby']中的一种
        code: 要执行的代码

    Returns:
        代码执行的输出结果
    """
    # 导入代码执行工具的必要模块
    try:
        SUPPORTED_LANGS = {'python', 'java', 'javascript', 'cpp', 'go', 'ruby'}
        if lang.lower() not in SUPPORTED_LANGS:
            return json.dumps({"error": "不支持的语言"}, ensure_ascii=False)



        # 安全策略
        security_policy = PYTHON_POLICY if lang.lower() == "python" else None
        print(security_policy)
        container_id = f"my_{lang.lower()}_container"

        try:
            client = docker.from_env()
            with SandboxSession(
                    lang=lang.upper(),
                    backend=SandboxBackend.DOCKER,
                    verbose=True,
                    container_id=container_id,
                    client=client,
                    execution_timeout=30,
                    security_policy=security_policy
            ) as session:
                is_safe, violations = session.is_safe(code)
                print(is_safe)
                print(violations)
                if not is_safe:
                    violations_str = ", ".join([v.description for v in violations])
                    return json.dumps({"error": f"安全检查未通过: {violations_str}"}, ensure_ascii=False)

                # Execute safely
                try:
                    resultOutput = session.run(code)
                    result=resultOutput.stdout
                    stderr = resultOutput.stderr
                    if stderr:
                        return json.dumps({"error": f"执行错误: {stderr}"}, ensure_ascii=False)
                    return json.dumps({"result": result}, ensure_ascii=False)
                except Exception as e:
                    return json.dumps({"error": f"执行错误: {e}"}, ensure_ascii=False)
        except DockerException as de:
            return json.dumps({"error": f"Docker操作失败: {de}"}, ensure_ascii=False)
        except Exception as e:
            return json.dumps({"error": f"未处理的异常: {e}"}, ensure_ascii=False)
    except ImportError as e:
        return json.dumps({"error": f"缺少必要的依赖库: {e}"}, ensure_ascii=False)


if __name__ == "__main__":
    # This code only runs when the file is executed directly

    # Basic run with default settings (stdio transport)
    mcp.run(transport="sse",host="0.0.0.0", port=9000,path="/mymcp")

    # Or with specific transport and parameters
    # mcp.run(transport="sse", host="127.0.0.1", port=9000)
